<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="scripts/chrome_ex_oauthsimple.js"></script>
    <script type="text/javascript" src="scripts/chrome_ex_oauth.js"></script>
    <script type="text/javascript">
        var APP_NAME = "tuishuo";
        var APP_VERSION = "0.1";

        var oauth = {};
		var stateTimer;

        function initConfig() {
            var oauthConfig = [
/*
App Key：1352117998
App Secret：95b809b8597b362c828897dc5e1ba6eb

2076114902
6ea0d501d5187a2b97847f5783fe8ae3
*/
                {'site':'weibo.com',
                    'requestUrl':'http://api.t.sina.com.cn/oauth/request_token',
                    'authorizeUrl': 'http://api.t.sina.com.cn/oauth/authorize',
                    'accessUrl': 'http://api.t.sina.com.cn/oauth/access_token',
                    'consumerKey': '1352117998',
                    'consumerSecret': '95b809b8597b362c828897dc5e1ba6eb',
                    'userInfoUrl': 'http://api.t.sina.com.cn/account/verify_credentials.json'}
/*
                {'site': 't.qq.com',
                    'requestUrl': 'https://open.t.qq.com/cgi-bin/request_token',
                    'authorizeUrl': 'https://open.t.qq.com/cgi-bin/authorize',
                    'accessUrl': 'https://open.t.qq.com/cgi-bin/access_token',
                    'consumerKey': '321b716677b84b8c8bb569f0e95bab67',
                    'consumerSecret': 'a39c83145b58cdfb06193055fb49cf14',
                    'userInfoUrl': 'http://open.t.qq.com/api/user/info?format=json'}
*/
                ];
            localStorage['oauthConfig'] = JSON.stringify(oauthConfig);

            for(var i=0; i<oauthConfig.length; i++) {
                //console.log(oauthConfig[i]);
                oauth[oauthConfig[i].site] = ChromeExOAuth.initBackgroundPage({
                    'request_url': oauthConfig[i].requestUrl,
                    'authorize_url': oauthConfig[i].authorizeUrl,
                    'access_url': oauthConfig[i].accessUrl,
                    'consumer_key': oauthConfig[i].consumerKey,
                    'consumer_secret': oauthConfig[i].consumerSecret,
                    'scope': oauthConfig[i].site,
                    'app_name': APP_NAME
                });
                //console.log(oauth[oauthConfig[i].site]);
            }
        }

		function checkState() {
			if (localStorage['stopCheck'] != null && localStorage['stopCheck'] == "1") {
				return;
			}

			var currentSite = 'weibo.com';
	        var boundSites = (localStorage['boundSites'] == null) ? {} : JSON.parse(localStorage['boundSites']);
	        var curUser = boundSites[currentSite].originalUser;
	        var params = (localStorage["lastId"] == null) ? {} : {'with_new_status':1, 'since_id':localStorage["lastId"]};

			oauth[currentSite].sendSignedRequest(
                'http://api.t.sina.com.cn/statuses/unread.json',
                function(res, xhr) {
					console.log(res);
                    localStorage['unreadState'] = res;
					var state = JSON.parse(res);
					if (state['status'] > 0) {
						chrome.browserAction.setBadgeText({'text':state['status'].toString()});
					}
                },
                {"method": 'GET', "parameters": params}
            );
		}

        function onRequest(request, sender, callback) {
            switch(request.action) {
                case "oauth":
                    oauth[request.site].authorize(function() {
                        oauth[request.site].sendSignedRequest(
                            request.data.userInfoUrl,
                            function(res, xhr) {
                                var boundSites = (localStorage['boundSites'] == null) ? {} : JSON.parse(localStorage['boundSites']);
                                boundSites[request.data.site] = { 'user': {}, 'originalUser': JSON.parse(res) };
                                localStorage['boundSites'] = JSON.stringify(boundSites);

                                callback();
                            },
                            {"method": "GET", "parameters": {}});
                    });
                    break;
                case "apply":
                    oauth[request.site].sendSignedRequest(
                        request.api,
                        function(res, xhr) {
                            callback(JSON.parse(res), xhr);
                        },
                        {"method": request.method, "parameters": request.parameters, "body": request.body, "headers": request.headers}
                    );
                    break;
                case "upload":
                    var authHeader = oauth[request.site].getAuthorizationHeader(request.api, 'POST', {'status': request.parameters['status']});

                    var fdata = new FormData();
                    fdata.append('status', request.parameters['status']);
                    fdata.append('pic', request.parameters['pic']);

                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', request.api, false);

                    xhr.addEventListener('load', function(e) {
                        if (callback) callback(JSON.parse(xhr.responseText));
                    }, false);

                    xhr.setRequestHeader('Authorization', authHeader);
                    xhr.send(fdata);
                    break;
                default:
                    break;
            }
        }

        function menuClick(info, tab) {
console.log("item " + info.menuItemId + " was clicked");
console.log("info: " + JSON.stringify(info));
console.log("tab: " + JSON.stringify(tab));
            var data = {"title": tab.title,
                        "url": tab.url}
            chrome.tabs.sendRequest(tab.id, {"type": "sharePage", "data": tab}, function(response) {
            });
        }

        (function() {
            initConfig();
			setInterval(checkState, 1000*60*3);
            var menu = chrome.contextMenus.create({"title": "用#推说#分享到微博", "onclick":menuClick});
        })();

        chrome.extension.onRequest.addListener(onRequest);
    </script>
</head>
<body>
<script src="scripts/tracker.js"></script>
</body>
</html>
